0-1 Knapsack Algorithm

The 0-1 Knapsack Algorithm is a classic optimization problem in computer science and combinatorics, where the goal is to determine the most valuable combination of items to include in a knapsack without exceeding its weight capacity. Given a set of items, each with a weight and a value, the algorithm aims to maximize the total value of the items placed in the knapsack while ensuring that the total weight does not exceed the knapsack's limit. The 0-1 nature of the problem refers to the fact that each item can either be included or excluded from the knapsack, without any fractional parts or repetitions. To solve the 0-1 Knapsack Problem, dynamic programming is often used as it breaks the problem down into smaller overlapping subproblems and builds a solution from the bottom up. The algorithm constructs a table with rows representing the items and columns representing the possible weight capacities of the knapsack. Each cell in the table holds the maximum value that can be achieved using the current set of items and the current weight capacity. The final solution can be found in the bottom-right cell of the table, representing the maximum value that can be achieved using all the items and the full capacity of the knapsack. The 0-1 Knapsack Algorithm is widely used in various fields such as finance, logistics, and resource allocation due to its effectiveness in solving complex optimization problems.
//0-1 Knapsack problem - Dynamic programming
//#include <bits/stdc++.h>
#include <iostream>
using namespace std;

//void Print(int res[20][20], int i, int j, int capacity)
//{
//	if(i==0 || j==0)
//	{
//		return;
//	}
//	if(res[i-1][j]==res[i][j-1])
//	{
//		if(i<=capacity)
//		{
//			cout<<i<<" ";
//		}
//
//		Print(res, i-1, j-1, capacity-i);
//	}
//	else if(res[i-1][j]>res[i][j-1])
//	{
//		Print(res, i-1,j, capacity);
//	}
//	else if(res[i][j-1]>res[i-1][j])
//	{
//		Print(res, i,j-1, capacity);
//	}
//}

int Knapsack(int capacity, int n, int weight[], int value[])
{
	int res[20][20];
	for (int i = 0; i < n + 1; ++i)
	{
		for (int j = 0; j < capacity + 1; ++j)
		{
			if (i == 0 || j == 0)
				res[i][j] = 0;
			else if (weight[i - 1] <= j)
				res[i][j] = max(value[i - 1] + res[i - 1][j - weight[i - 1]], res[i - 1][j]);
			else
				res[i][j] = res[i - 1][j];
		}
	}
	//	Print(res, n, capacity, capacity);
	//	cout<<"\n";
	return res[n][capacity];
}
int main()
{
	int n;
	cout << "Enter number of items: ";
	cin >> n;
	int weight[n], value[n];
	cout << "Enter weights: ";
	for (int i = 0; i < n; ++i)
	{
		cin >> weight[i];
	}
	cout << "Enter values: ";
	for (int i = 0; i < n; ++i)
	{
		cin >> value[i];
	}
	int capacity;
	cout << "Enter capacity: ";
	cin >> capacity;
	cout << Knapsack(capacity, n, weight, value);
	return 0;
}

LANGUAGE:

DARK MODE: